package com.jams.goodox.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.TownApplicationLike;
import com.jams.goodox.activity.login.LoginActivity;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.MeetDateBean;
import com.jams.goodox.entity.MeetMonthDate;
import com.jams.goodox.entity.resp.MeetCalendarResp;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.services.LoginService;

import java.io.File;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by jams on 2017/4/19.
 * ***
 * Tel: ***
 *
 * 普通的工具类
 */

public class Utils {

    private static long lastClickTime;
    /**
     * 防止多次点击
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if ((0 < timeD && timeD < 500)||timeD<0) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    static TextView cutDownText;
    private static CountDown down;
    static int a;

    // 倒计时
    public static void countDown(int seconds, final TextView t, final BaseResult result) {
        a = seconds;
        result.onStart();
        cutDownText = t;
        down = new CountDown(result);
        handler.postDelayed(down, 1000);
    }

    private static android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && cutDownText != null) {
                cutDownText.setText(String.format("%d秒后重发", msg.arg1));
            }
        }
    };

    private static class CountDown implements Runnable {
        BaseResult result;

        public CountDown(BaseResult result) {
            this.result = result;
        }


        @Override
        public void run() {
            if (a > 0) {
                a--;
                Message msg = new Message();
                msg.arg1 = a;
                handler.sendMessage(msg);
                handler.postDelayed(this, 1000);
            } else {
                result.onResult(true);
            }
        }
    }


    public interface BaseResult {
        void onStart();

        void onResult(Boolean t);
    }

    /**
     * 设置非法字符（数字+特殊字符过滤器）
     *
     * @param editText
     */
    public static void setFilter(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String editable = editText.getText().toString();
                String str = stringFilter(editable);
                if (!editable.equals(str)) {
                    editText.setText(str);
                    //设置新的光标所在位置
                    editText.setSelection(str.length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    public static void setFilterNoNumber(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String editable = editText.getText().toString();
                String str = stringFilterNoNumber(editable);
                if (!editable.equals(str)) {
                    editText.setText(str);
                    //设置新的光标所在位置
                    editText.setSelection(str.length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static String stringFilterNoNumber(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字
        String regEx = "[^a-zA-Z\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static boolean isExists(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return false;
        }
        File file = new File(fileName);
        return file.exists();
    }

    public static void addView(Context context, ViewGroup view, LinearLayout layout, int icon, int text) {
        removeView(view, layout);
        if (layout == null) {
            return;
        }
        layout.findViewById(R.id.no_icon).setBackgroundResource(icon);
        TextView tv = (TextView) layout.findViewById(R.id.no_text);
        tv.setText(text);
        view.addView(layout);
    }

    public static void removeView(ViewGroup view, LinearLayout layout) {
        if (view != null) {
            view.removeView(layout);
        }
    }

    /**
     * 车牌输入
     * 中英文数字输入，过滤小写
     * @param editText
     */
    public static void editInputToLarge(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String editable = editText.getText().toString();
                String str = stringFilter(editable);
                if (!editable.equals(str)) {
                    editText.setText(str);
                    //设置新的光标所在位置
                    editText.setSelection(str.length());
                }
                int a = editText.getSelectionEnd();
                if (str.matches("[A-Z\u4e00-\u9fa5\0-9]*")) return;
                else {
                    editText.setText(str.toUpperCase());
                    editText.setSelection(a);
                }
            }
        });
    }

    static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式

    public static String getNowDate() {
        return df.format(new Date());
    }

    //
    public static String getDate(int dateAdd) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.DATE, dateAdd);//把日期往后增加一天.整数往后推,负数往前移动
        Date date = calendar.getTime();   //这个时间就是日期往后推一天的结果
        return df.format(date);
    }


    public static String reDoDate(String dateStr,boolean isAdd){
        try {
            Date classDate = df.parse(dateStr);//把字符串转化成指定格式的日期
            Calendar calendar = Calendar.getInstance(); //使用Calendar日历类对日期进行加减
            calendar.setTime(classDate);
            calendar.add(Calendar.DAY_OF_MONTH, isAdd?1:- 1);
            classDate = calendar.getTime();//获取加减以后的Date类型日期
            String a=df.format(classDate);
            return df.format(classDate);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取今天起一周
     *
     * @return
     */
    public static String[] getWeekDates() {
        String[] dateList = new String[7];
        for (int i = 0; i < 7; i++) {
            dateList[i] = getDate(i);
        }
        return dateList;
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    public static Bitmap buildQRCode(ImageView imageView, String contentString, Context mContext) {
        try {
            if (contentString != null && contentString.trim().length() > 0) {
                // 根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小
                return null;
            } else {
                ToastUtil.showShort(mContext, "二维码生成失败，请重新生成");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将2015-12-11转化为2015年12月11日
     *
     * @param dateTime
     * @return
     */
    public static String getStringDate(String dateTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatTo = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            Date date = formatter.parse(dateTime);
            return formatTo.format(date);
        } catch (Exception e) {
            return dateTime;
        }
    }

    /**
     * 获取状态栏高度
     * @param context
     * @return
     */
    public static int getStateBarHeight(Activity context) {
        Rect frame = new Rect();
        context.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        return statusBarHeight;
    }

    public static Bitmap takeScreenShot(Activity activity) {
        // View是你需要截图的View
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();
        // 获取屏幕长和高
        //noinspection deprecation
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        //noinspection deprecation
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();

        int statusBarHeight = getStateBarHeight(activity);
        // 去掉标题栏 //Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
        Bitmap b = Bitmap.createBitmap(b1, 0,
                statusBarHeight + activity.getResources().getDimensionPixelSize(R.dimen.item_size), width,
                height - statusBarHeight - activity.getResources().getDimensionPixelSize(R.dimen.item_size)
                        - activity.getResources().getDimensionPixelSize(R.dimen.item_size));
        view.destroyDrawingCache();
        return b;
    } // 保存到sdcard

    public static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yy-MM-dd");
    /**
     * string 转化为date
     *
     * @param date yyyy-MM-dd
     * @return
     */
    public static Date getDateByString(String date) {

        try {
            Date selectDate = FORMATTER.parse(date);
            return selectDate;
        } catch (ParseException p) {
        }
        return null;
    }
    /**
     * 处理手机号码
     * @param phoneNum 手机号码
     * @return 中间4位以****替代
     */
    public static String getStarPhoneNum(String phoneNum) {
        if (null != phoneNum && phoneNum.length() == 11) {
            return phoneNum.substring(0, 3) + "****" + phoneNum.substring(7, 11);
        }
        return phoneNum;
    }

    public static Map<String, String> getParamsWithBase(Context c) {
        Map<String, String> params = new HashMap<>();
        if (!TextUtils.isEmpty(SePref.getCommunityId()))
            params.put("communityId", SePref.getCommunityId());
        if (!TextUtils.isEmpty(SePref.getToken())) {
            params.put("token", SePref.getToken());
        }
        params.put("version", AppConfig.VERSION);
        params.put("fieds", "version");
        params.put("sign", SecureUtils.getSHA(AppConfig.VERSION + AppConfig.KEY));
        params.put("companyCode", AppConfig.COMPANY_CODE);
        params.put("mobileType", AppConfig.MOBILE_TYPE);
        try {
            if (!TextUtils.isEmpty(android.os.Build.MODEL))
                params.put("mobileName", android.os.Build.MODEL);
            if (!TextUtils.isEmpty(android.os.Build.VERSION.RELEASE))
                params.put("mobileVersion", android.os.Build.VERSION.RELEASE);
            if (!TextUtils.isEmpty(AppConfig.getAndroidId(TownApplicationLike.getInstance())))
                params.put("mobileNo", AppConfig.getAndroidId(TownApplicationLike.getInstance()));
        } catch (Exception e) {

        }
        params.put("appVersion", "" + Utils.getVersionName());
        return params;
    }

    public static String getVersionName() {
        try {
            return TownApplicationLike.getInstance().getPackageManager().getPackageInfo(TownApplicationLike.getInstance().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 只有中英文
     *
     * @param str
     * @return 只是中英文就返回true
     */
    public static boolean justTxt(String str) {
        return str.matches("[a-zA-Z\u4e00-\u9fa5]*");
    }

    /**
     * ------------------------------------------
     *
     * @param phone
     * @return
     * @desc 判断是否是手机号码 ------------------------------------------
     */
    public static boolean isPhoneNum(String phone) {
        if (TextUtils.isEmpty(phone)) {
            return false;
        } else {
            Pattern phoMat = Pattern.compile("[1][0-9]{10}");
            Matcher matcher = phoMat.matcher(phone);
            return matcher.matches();
        }
    }

    /**
     * 传入的时间加上和当前时间比较
     *
     * @param date 传入的时间
     * @return false 传入的时间小于当前时间 true 传入的时间大于当前时间
     */
    public static boolean timeCurrentCompare(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 向指定日历字段添加指定（有符号的）时间量，更改更大的字段。
        return (cal.getTime().compareTo(new Date())) < 0 ? false : true;
    }

    /**
     * 计算时间差
     *
     * @param startTime
     * @param TargetTime
     * @return true 返回时间大于15
     */
    public static boolean timeDivide(String startTime, String TargetTime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date d1 = df.parse(startTime);
            Date d2 = df.parse(TargetTime);
            long diff = d2.getTime() - d1.getTime();
            long minutes = diff / (1000 * 60);
            if (minutes >= 15) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 德奥当前时间
     *
     * @return
     */
    public static String currentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(new Date());
    }

    // 提醒输入框最大输入字数
    public static void controlEdtCount(final EditText editText, final int mCount, final Context mContext) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

                EditTextLimitUtils.lengthFilter(mContext, editText, mCount, false);
            }
        });
    }

    public static int getIntByStr(String str){
        try {
            return (int)Double.parseDouble(str);
        }catch (Exception e){
            return 0;
        }
    }

    /**
     * 清除用户信息
     */
    public static void clearUserInfo(Context context) {
        SePref.setPrePhone(SePref.getUserPhone());
        SePref.clearUserInfo();
        DataCacheManager.getInstance().deleteAllUserData();
        DataCacheManager.getInstance().setUser(null);
    }

    public static void logOut(Context context){//此处要解决登陆闪屏的问题
        doLogOut(context);//接口推出登陆
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setClass(context, LoginActivity.class);
        context.startActivity(intent);
        ((Activity)context).finish();
        SePref.putToken("");
        clearUserInfo(context);//清除本地信息
    }

    /**
     * 通知后台退出登录
     * @param context 此activity需要继承baseActivity才可以执行该请求
     */
    public static void doLogOut(Context context){
        if(context instanceof Activity){
            ProtocolManagers.getInstance(context).getService(LoginService.class).logOut().enqueue(new Callback<BaseEntity>() {
                @Override
                public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {

                }

                @Override
                public void onFailure(Call<BaseEntity> call, Throwable t) {

                }
            });
        }
    }

    /**
     * 根据某个分隔符，分割字符串
     * @param splitStr 待分割的字符串
     * @param separator 分隔符
     * @return 分割完成的列表
     */
    public static List<String> getListByString(String splitStr,String separator){
        List<String> strList=new ArrayList<>();
        if(TextUtils.isEmpty(splitStr)||TextUtils.isEmpty(separator))return strList;
        if(splitStr.contains(separator)){
            String[] splits=splitStr.split(separator);
            if(splits!=null){
                for (int i=0;i<splits.length;i++){
                    if(!TextUtils.isEmpty(splits[i])) strList.add(splits[i]);
                }
            }
        }else {
            strList.add(splitStr);
        }
        return strList;
    }

    final static SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 根据日期字符串获取周几
     * @param dateTime 日期字符串“2017-6-2”
     * @return 周一
     */
    public static final String getWeekByStr(String dateTime){
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        try {
            Date date =sdf.parse(dateTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return  weekDays[calendar.get(Calendar.DAY_OF_WEEK)-1];
        }catch (Exception e){
            e.printStackTrace();
        }
        return "周一";
    }

    /**
     * 获取类似12月25日 by 2017-02-20
     * @param dateTime 2017-02-20
     * @return 12月25日
     */
    public static final String getMonthStr(String dateTime){
        try {
            Date date =sdf.parse(dateTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
            return sdf.format(calendar.getTime());
        }catch (Exception e){
            e.printStackTrace();
        }
        return "11月11日";
    }

    /**
     * 根据2016-12获取2016年12月
     * @param dateTime 2016-12
     * @return
     */
    public static final String getYearMonthStr(String dateTime){
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM");
        try {
            Date date =sdf.parse(dateTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            SimpleDateFormat sdfs = new SimpleDateFormat("yyyy年MM月");
            return sdfs.format(calendar.getTime());
        }catch (Exception e){
            e.printStackTrace();
        }
        return "11月11日";
    }

    public static final int getDayOfMonth(String dateTime){
        try {
            Date date =sdf.parse(dateTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar.get(Calendar.DAY_OF_MONTH);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取日期
     * @param dateStr 待转字符串
     * @return 日期
     */
    public static Date getDateByStr(String dateStr){
        try{
            return sdf.parse(dateStr);
        }catch (Exception e){
            return new Date();
        }
    }

    /**
     * 好司机带带我，获取订单时间
     * @param date 订单时间戳
     * @return
     */
    public static String getFormatDateStr(long date){
        try {
            String day;
            Calendar mowCalendar=Calendar.getInstance();
            Calendar tomorrowCalendar=Calendar.getInstance();
            tomorrowCalendar.add(Calendar.DATE,1);
            Calendar dateCalendar=Calendar.getInstance();
            dateCalendar.setTime(new Date(date));

            clearCalendar(mowCalendar, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND);
            clearCalendar(tomorrowCalendar, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND);
            clearCalendar(dateCalendar, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND);

            if(mowCalendar.getTime().compareTo(dateCalendar.getTime())==0){
                day="今天";
            }else if(tomorrowCalendar.getTime().compareTo(dateCalendar.getTime())==0){
                day="明天";
            }else {
                return new SimpleDateFormat("MM-dd HH:mm").format(date);
            }
            return String.format("%s%s",day,new SimpleDateFormat("HH:mm").format(date));
        }catch (Exception e){
            return "";
        }
    }

    private static void clearCalendar(Calendar c, int... fields) {
        for (int f : fields) {
            c.set(f, 0);
        }
    }

    /**
     * 获取某个月的数据列表
     * @return
     */
    public static List<MeetDateBean> getMeetMonthList(String monthStr){
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM");
        List<MeetDateBean> meetDateBeanList=new ArrayList<>();
        try {
            Date date =sdf.parse(monthStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int monthLength=calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            for(int i=1;i<=monthLength;i++){
                MeetDateBean meetDateBean=new MeetDateBean();
                meetDateBean.setDateStr(i+"");
                calendar.set(Calendar.DAY_OF_MONTH,i);//设置为1号,当前日期既为本月第一天
                meetDateBean.setDate(calendar.getTime());
                meetDateBeanList.add(meetDateBean);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return meetDateBeanList;
    }

    /**
     * 获取场地预定的日历全列表
     * @param listBeen 后台提供的预定场次 ：可预定 有 无
     * @return 全列表
     */
    public static List<MeetMonthDate> getMeetAllLists(List<MeetCalendarResp.DataBean> listBeen){
        if(listBeen==null||listBeen.size()==0)return null;
        List<MeetMonthDate> meetMonthDateList=new ArrayList<>();
        try {
            for(int i=0;i<listBeen.size();i++){
                MeetMonthDate meetMonthDate=new MeetMonthDate();
                meetMonthDate.setMonthOfYear(getYearMonthStr(listBeen.get(i).getYMonth()));
                meetMonthDate.setMeetDateBeenList(getMeetDateBeenList(listBeen.get(i)));
                meetMonthDateList.add(meetMonthDate);
            }
        }catch (Exception e){

        }
        return meetMonthDateList;
    }

    /**
     * 获取场地预定的某月列表
     * @param dataBean 后台返回的某个月的实体
     * @return 月列表
     */
    private static List<MeetDateBean> getMeetDateBeenList(MeetCalendarResp.DataBean dataBean){
        List<MeetDateBean> meetDateBeanList=getMeetMonthList(dataBean.getYMonth());
        List<MeetCalendarResp.DataBean.DateListBean> dateList=  dataBean.getDateList();
        for(MeetCalendarResp.DataBean.DateListBean dateListBean:dateList){
            int position=getDayOfMonth(dateListBean.getPlaceOpenDate())-1;
            meetDateBeanList.get(position).setCanReserve(true);
            meetDateBeanList.get(position).setHavePlace(dateListBean.getHasPlace()==0);
        }
        return meetDateBeanList;
    }

    /**
     * 根据编辑框获取数值
     * @param numberEdit 编辑框
     * @return
     */
    public static float getFloatValueByEditText(EditText numberEdit){
        String str=numberEdit.getText().toString().trim();
        try {
            return TextUtils.isEmpty(str)?0:Float.parseFloat(str);
        }catch (Exception e){
            return 0;
        }
    }

    /**
     * 根据编辑框获取整数数值
     * @param numberEdit
     * @return
     */
    public static int getIntValueByEditText(EditText numberEdit){
        return (int)getFloatValueByEditText(numberEdit);
    }

    public static String getFormatDateByString(String dateStr){
        Calendar calendar=Calendar.getInstance();
        String year=String.valueOf(calendar.get(Calendar.YEAR));
        return String.format("%s-%s",year,dateStr);
    }

    public static String setEndTime(int n, String time) {
        try {
            Calendar calendar = stringToCalendar(time);
            int month = calendar.get(Calendar.MONTH);
            int startDay = calendar.get(Calendar.DAY_OF_MONTH);
            if ((n + month) > 12) {
                calendar.add(Calendar.YEAR, 1);
                calendar.add(Calendar.MONTH, n - 12);
            } else {
                calendar.add(Calendar.MONTH, n);
            }
            int endDays = getCurrentMonthDay((new SimpleDateFormat("yyyy-MM-dd")).format(calendar.getTime()));
            int differ = startDay - endDays;//
            if(differ<=0){
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1);
            }
            return (new SimpleDateFormat("yyyy-MM-dd")).format(calendar.getTime());
        }catch (Exception e){
            e.printStackTrace();
            return "2017-12-12";
        }
    }
    /**
     * 获取当月的 天数
     * */
    public static int getCurrentMonthDay(String calendar) {
        Calendar a = stringToCalendar(calendar);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        return  a.get(Calendar.DATE);
    }

    public static Calendar stringToCalendar(String strTime) {
        // 创建 Calendar 对象
        Calendar calendar = Calendar.getInstance();
        try {
            // 对 calendar 设置时间的方法
            // 设置传入的时间格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = dateFormat.parse(strTime);
            // 对 calendar 设置为 date 所定的日期
            calendar.setTime(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return calendar;
    }

    public static String getStrByLong(long dateTime){
        try {
            Date date=new Date(dateTime);
            return   sdf.format(date);
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 控制textView背景&字体颜色改变
     * @param tx 需要修改的textView
     * @param isChoose true:背景主题色，字体黑色 false：背景白色黑框，字体灰色
     */
    public static void setTextChange(TextView tx, boolean isChoose) {
        if (isChoose) {
            tx.setBackgroundResource(R.drawable.bg_cancel_theme);
            tx.setTextColor(ContextCompat.getColor(TownApplicationLike.getInstance(), R.color.font_color_black));
        } else {
            tx.setBackgroundResource(R.drawable.bg_cancel_white_black);
            tx.setTextColor(ContextCompat.getColor(TownApplicationLike.getInstance(), R.color.font_color_gray));
        }
    }

    /**
     * 两个double相加
     * @return 相加后的值
     */
    public static  double AddTwoValue(double value1 ,double value2){
        BigDecimal bigDecimal1=new BigDecimal(String.valueOf(value1));
        BigDecimal bigDecimal2=new BigDecimal(String.valueOf(value2));
        return bigDecimal1.add(bigDecimal2).doubleValue();
    }

    /**
     * 两个double相减
     * @return value1-value2
     */
    public static  double SubtractTwoValue(double value1 ,double value2){
        BigDecimal bigDecimal1=new BigDecimal(String.valueOf(value1));
        BigDecimal bigDecimal2=new BigDecimal(String.valueOf(value2));
        return bigDecimal1.subtract(bigDecimal2).doubleValue();
    }

    /**
     * 此处调用该方法设置某模块已经使用过了
     * @param functionName 模块名
     */
    public static void putFunctionOpen(String functionName){
        if(TextUtils.isEmpty(SePref.getUserId()))return;
        String key=functionName+SePref.getUserId();
        SePref.setFunctionOpened(key,true);
    }

    /**
     * 获取某个模块，某用户是否已经打开过，默认false;同时默认设置已经打开
     * @param functionName 模块名
     * @return true:未登录or已经打开 false：当前用户第一次打开该模块
     */
    public static boolean getFunctionIsOpen(String functionName){
        if(TextUtils.isEmpty(SePref.getUserId()))return true;
        String key=functionName+SePref.getUserId();
        return SePref.getFunctionIsOpen(key);
    }

    /**
     * 用于app某用户第一次打开某个模块，弹窗提示
     * @param context 页面
     * @param functionName 模块名称，取值
     * @param hintRes 提示文案
     */
    public static void doFunctionIsOpen(Context context,String functionName,int hintRes){
        doFunctionIsOpen(context,functionName,context.getString(hintRes));
    }

    /**
     * 用于app某用户第一次打开某个模块，弹窗提示
     * @param context 页面
     * @param functionName 模块名称，取值
     * @param hint 提示文案
     */
    public static void doFunctionIsOpen(Context context,String functionName,String hint){
        if(getFunctionIsOpen(functionName))return;
        putFunctionOpen(functionName);
        new MaterialDialog.Builder(context).content(hint).positiveText("知道了").cancelable(false).show();
    }

    public static String formatDateTime(String dateTime){
        try {
            if(TextUtils.isEmpty(dateTime))return "";
            SimpleDateFormat sdf1= new SimpleDateFormat("MMM dd yyyy HH:mm:ss z ", Locale.ENGLISH);
            SimpleDateFormat sdf2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf2.format(sdf1.parse(dateTime));
        }catch (ParseException e){
            return "";
        }
    }

    public static String formatDateTime(long data){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return formatter.format(new Date(data));
    }

}
